package cn.mesmile.flow.utils;

import cn.hutool.core.util.IdUtil;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author zb
 * @date 2020/12/8 10:03
 * @Description
 */
public class IdUtils {

    private IdUtils(){}

    /**
     * 订单号生成
     **/
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");
    private static final AtomicInteger SEQ = new AtomicInteger(1000);
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyMMddHHmmss");

    /**
     * 生成订单号
     *
     * @return
     */
    public static String generateNumber() {
        LocalDateTime dataTime = LocalDateTime.now(ZONE_ID);
        if (SEQ.intValue() > 9000) {
            SEQ.getAndSet(1000);
        }
        // String.format("%4d", andIncrement).replace(" ", "0");
        return dataTime.format(DF_FMT_PREFIX) + SEQ.getAndIncrement();
    }


    public static void main(String[] args) {
        List<String> orderNos = Collections.synchronizedList(new ArrayList<String>());

        System.out.println("generateNumber() = " + generateNumber());
        // 8000 次并发
        IntStream.range(0, 8000).parallel().forEach(i -> {
            orderNos.add(generateNumber());
        });
        List<String> filterOrderNos = orderNos.stream().distinct().collect(Collectors.toList());
        System.out.println(orderNos.size());
        System.out.println(filterOrderNos.size());
    }

}
